package com.abacus.salary.dao;

public class TransactionProvider implements Transaction {

	private org.hibernate.Transaction tx;

	@Override
	public void begin() {
		if (tx != null) {
			throw new RuntimeException("the transaction is not null ");
		}
		tx = SessionProvider.getCurrentSession().beginTransaction();
	}

	@Override
	public void commit() {
		if (null != tx) {
			tx.commit();
			tx = null;
		}
	}

	@Override
	public void rollback() {
		if (null != tx && tx.isActive()) {
			tx.rollback();
			tx = null;
		}
	}

	private static final ThreadLocal<Transaction> threadLocal = new ThreadLocal<Transaction>();

	public static synchronized final Transaction getTransaction() {
		Transaction transaction = threadLocal.get();
		if (null == transaction) {
			transaction = new TransactionProvider();
			threadLocal.set(transaction);
		}
		return transaction;
	}

}
